package com.chinasofti.framework.net;

import java.util.ArrayList;
import java.util.HashMap;

import com.chinasofti.framework.base.App;
import com.chinasofti.framework.data.Entity;
import com.chinasofti.framework.data.FieldType;
import com.chinasofti.framework.dataaccess.Filter;
import com.chinasofti.framework.dataaccess.Parameter;

public class Request<T extends Entity> extends Entity {
	public enum Action {
		LOAD_BY_KEY,
		LOAD_BY_FILTER,
		LOAD_BY_PARAMS,
		SAVE_SINGLE,
		SAVE_MULTI,
		SAVE_BY_PARAMS,
		DELETE_BY_KEY,
		DELETE_BY_FILTER,
		DELETE_BY_PARAMS
	}

	private static HashMap<String, FieldType> m_fields;
	private static final String ENTITY_NAME = "Request";
	private static final String KEY_FIELD = "";
	
	
	public Request() {
		init();
	}
	
	@Override
	protected void init() {
		if(m_fields == null) {
			m_fields = new HashMap<String, FieldType>();
			m_fields.put("Identity", new FieldType(String.class));
			m_fields.put("Action", new FieldType(Action.class));
			m_fields.put("SessionId", new FieldType(String.class));
			m_fields.put("Lat", new FieldType(Float.class));
			m_fields.put("Lon", new FieldType(Float.class));
			m_fields.put("Key", new FieldType(String.class));
			m_fields.put("Entities", new FieldType(Entity.class, false));
			m_fields.put("Filter", new FieldType(Filter.class));
			m_fields.put("Params", new FieldType(Parameter.class,false));
		}
		
		set("Identity", App.getInstance().getIdentity());
		set("SessionId", App.getInstance().getSessionId());
		set("Lat", App.getInstance().Location().Lat);
		set("Lon", App.getInstance().Location().Lon);
	}

	@Override
	public RequestParser getParser() {
		return new RequestParser();
	}

	@Override
	public HashMap<String, FieldType> getFieldTypes() {
		return m_fields;
	}

	@Override
	public String getKeyField() {
		return KEY_FIELD;
	}

	@Override
	public String getEntityName() {
		return ENTITY_NAME;
	}

	//自定义代�?
	
	public Request(ArrayList<Parameter> params) {
		init();
		set("Action", Action.LOAD_BY_PARAMS);
		set("Params", params);
	}
	
	public Request(Filter filter) {
		init();
		set("Action", Action.LOAD_BY_FILTER);
		set("Filter", filter);
	}
	
	public Request(Object key) {
		init();
		set("Action", Action.LOAD_BY_KEY);
		set("Key", key);
	}

	public Action getAction() {
		return (Action)get("Action");
	}
	
	public String getSessionId() {
		return getString("SessionId");
	}
	
	public Object getKey() {
		return get("Key");
	}

	@SuppressWarnings("unchecked")
	public ArrayList<T> getEntities() {
		return (ArrayList<T>)get("Entities");
	}
	
	public Filter getFilter() {
		@SuppressWarnings("unchecked")
		ArrayList<Filter> filters = (ArrayList<Filter>)get("Filter");
		if(filters != null && filters.size() != 0) {
			return filters.get(0);
		}
		return null;
	}
}
